<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
</head>
<body>
		<script type="text/javascript">
			
			/*
				对Ajax进行封装，要考虑那些的参数会发生变化
				请求地址：url
				传输方式：type(GET、POST)
				请求头：POST必须要有请求头
				传输数据的格式：data(json)
				open:async(true和false来控制传输的时候是同步还是异步)
				用对象来做传入参数
			*/
		   //创建ajax对象
		   function  ajax(options){
			   let xhr = null
			   //ajax对象的兼容性处理
			   if(window.XMLHttpRequest){
				   xhr = new XMLHttpRequest()
			   }else{
				   xhr = new ActiveXObject("Microft.XMLHTTP")
			   }
			   let params = formatParams(options.data)
			   //提交方式的而处理
			   if(options.type === "GET"){
				   xhr.open(options.type,options.url,options.async)
				   xhr.send()
			   }else if(options.type === "POST"){
				   xhr.open(options.type,options.url + "?" + params,options.async)
				   xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
				   xhr.send(params)
			   }
			   //判断服务器的变化，(利用状态码)
			   xhr.onreadystatechange = () => {
			   	if(xhr.readyState !==4) return 
			   	if(xhr.readyState === 4 || xhr.status === 200){
					options.success(xhr.responseText)
					}
			   }
			   //将options里面的json数据，传化成=形式的字符串
			   function formatParams(data){
				   let arr = []
				   for(let prop in data){
					   arr.push(prop + "=" + data[prop])
				   }
				   return arr.join('&')
			   }
		   }  
		   
		   ajax({
			   url:'req.php',
			   type:'GET',
			   async:true,
			   data:{
				   username:'zhangsan',
				   sex:'nv'
			   },
			   success:function(data){
				   console.log(data)
			   }
		   })
		</script>
</body>
</html>